package com.kedacom.demo.ad.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kedacom.demo.ad.model.ADUser;
import com.kedacom.demo.ad.model.ADUser.ADUserAttributesMapper;
import com.kedacom.demo.ad.service.ADUserService;

@Controller("adUserController")
@RequestMapping("/")
public class ADUserController {

	@Resource
	private ADUserService userService;

	@RequestMapping(value = {
			"/", "/index"
	}, method = RequestMethod.GET)
	public String index(Model model) {
		return login(model);
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model) {
		List<String> domains = userService.getDomains();
		model.addAttribute("domains", domains);
		return "/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Model model, String domain, String username, String password) {
		if (StringUtils.isNoneBlank(domain)) {
			username = domain + username;
		}
		ADUser user = userService.login(username, password);
		model.addAttribute("user", user);
		return "/login_result";
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String listAllUsers(Model model) {
		List<ADUser> users = userService.listUsers();
		model.addAttribute("users", users);
		return "/users";
	}

	@RequestMapping(value = "/attributes", method = RequestMethod.GET)
	public String listAttributes(Model model) {
		Map<String, String> attributes = ADUserAttributesMapper.attributeNames;
		model.addAttribute("attributes", attributes);
		return "/attributes";
	}

}
